package ${packageName}.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import ${packageName}.mapper.${ClassName}Mapper;
import ${packageName}.entity.${ClassName};
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
import ${packageName}.entity.${childTable.ClassName};
import ${packageName}.service.${childTable.ClassName}Service;
</#list>
</#if>
<#if tplCategory == "parent">
import ${packageName}.vo.${ClassName}VO;
</#if>
import ${packageName}.service.${ClassName}Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import com.hgyc.mom.common.exception.BizException;
import org.springframework.util.CollectionUtils;

<#-- 类注释 -->
/**
 * ${functionName}Service业务层实现
 *
 * @author ${author}
 * @since ${datetime}
*/
@Slf4j
@Service
public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper, ${ClassName}> implements ${ClassName}Service {

<#if tplCategory == "tree">
    @Override
    public List<${ClassName}> treeList(${ClassName}Param ${className}Param) {
        ${ClassName} ${className} = new ${ClassName}();
        BeanUtils.copyProperties(${className}Param, ${className});
        QueryWrapper<${ClassName}> wrapper = QueryWrapperUtil.build(${className});
        List<${ClassName}> list = list(wrapper);
        return this.convertToTree(list);
    }

    private List<${ClassName}> convertToTree(List<${ClassName}> ${className}List) {
        Map<Long, List<${ClassName}>> parentChildrenMap = new HashMap<>();
            for (${ClassName} ${className} : ${className}List) {
            Long parentId = ${className}.getParentId();

            // 将当前菜单项添加到父菜单项的子菜单项列表中
            List<${ClassName}> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
            children.add(${className});
            parentChildrenMap.put(parentId, children);

        }
        // 将根节点的子菜单项列表转换为树形结构
        List<${ClassName}> rootChildren = parentChildrenMap.getOrDefault(0L, new ArrayList<>());
            for (${ClassName} ${className} : rootChildren) {
                convertToTree(${className}, parentChildrenMap);
            }
            return rootChildren;
        }

    private void convertToTree(${ClassName} parent, Map<Long, List<${ClassName}>> parentChildrenMap) {
        Long parentId = parent.getId();
        List<${ClassName}> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
        parent.setChildren(children);
        for (${ClassName} child : children) {
            convertToTree(child, parentChildrenMap);
        }
    }
</#if>
<#if tplCategory == "parent">
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
    @Autowired
    private ${childTable.ClassName}Service ${childTable.className}Service;
</#list>
</#if>
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save${BusinessName}(${ClassName}VO ${className}VO) {
        // TODO 其他逻辑
        save(${className}VO);

<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
        //新增${childTable.functionName}
        List<${childTable.ClassName}> ${childTable.businessName}s = ${className}VO.getAdd${childTable.BusinessName}s();
            if (!CollectionUtils.isEmpty(${childTable.businessName}s)) {
                ${childTable.businessName}s.forEach(item -> {
                item.setId(null);
                item.set${childTable.ParentId}(${className}VO.get${table.pkColumn.javaField?uncap_first?cap_first}());
            });
            ${childTable.className}Service.saveBatch(${childTable.businessName}s);
        }
</#list>
</#if>
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update${BusinessName}(${ClassName}VO ${className}VO) {
        // TODO 其他逻辑
        updateById(${className}VO);

<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
        //删除${childTable.functionName}
        if (!CollectionUtils.isEmpty(${className}VO.getDelete${childTable.BusinessName}Ids())) {
            ${childTable.className}Service.removeBatchByIds(${className}VO.getDelete${childTable.BusinessName}Ids());
        }

        //新增${childTable.functionName}
        List<${childTable.ClassName}> ${childTable.businessName}s = ${className}VO.getAdd${childTable.BusinessName}s();
        if (!CollectionUtils.isEmpty(${childTable.businessName}s)) {
            ${childTable.businessName}s.forEach(item -> {
                item.setId(null);
                item.set${childTable.ParentId}(${className}VO.get${table.pkColumn.javaField?uncap_first?cap_first}());
            });
            ${childTable.className}Service.saveBatch(${childTable.businessName}s);
        }

        //更新${childTable.functionName}
        if (!CollectionUtils.isEmpty(${className}VO.getUpdate${childTable.BusinessName}s())) {
            List<${childTable.ClassName}> update${childTable.BusinessName}s = ${className}VO.getUpdate${childTable.BusinessName}s();
            ${childTable.className}Service.updateBatchById(update${childTable.BusinessName}s);
        }
</#list>
</#if>
     }

     @Override
     @Transactional(rollbackFor = Exception.class)
     public void remove${BusinessName}(List<Long> ids) {
        // TODO 其他逻辑
         removeByIds(ids);
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
        //删除${childTable.functionName}
        ${childTable.className}Service.deleteBatchByParentIds(ids);
</#list>
</#if>
     }

<#elseif tplCategory == "crud" || tplCategory == "tree">
    @Override
    public void save${BusinessName}(${ClassName} ${className}) {
        // TODO 其他逻辑
        save(${className});
    }

    @Override
    public void update${BusinessName}(${ClassName} ${className}) {
        // TODO 其他逻辑
        updateById(${className});
    }

    @Override
    public void remove${BusinessName}(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
    }
</#if>
<#if tplCategory == "children">
    @Override
    public List<${ClassName}> getByParentId(Long parentId) {
        LambdaQueryWrapper<${ClassName}> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(${ClassName}::get${ParentId}, parentId);
        return list(wrapper);
        }

    @Override
    public void deleteByParentId(Long parentId) {
        LambdaQueryWrapper<${ClassName}> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(${ClassName}::get${ParentId}, parentId);
        remove(wrapper);
    }

    @Override
    public void deleteBatchByParentIds(List<Long> parentIds) {
        LambdaQueryWrapper<${ClassName}> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(${ClassName}::get${ParentId}, parentIds);
        remove(wrapper);
    }
</#if>
<#if tplCategory == "crud" || tplCategory == "parent">

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<${ClassName}> ${className}List, boolean updateSupport) {
        if (${className}List == null || ${className}List.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + ${className}List.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + ${className}List.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("${functionName}导入失败", e);
            throw new BizException("${functionName}导入失败：" + e.getMessage());
        }
    }
</#if>
}